package com.allen.controller;

import com.allen.bean.OrderDetail;
import com.allen.bean.Orders;
import com.allen.bean.ShoppingCart;
import com.allen.common.BaseContext;
import com.allen.common.R;
import com.allen.dto.OrdersDto;
import com.allen.service.OrderDetailService;
import com.allen.service.OrderService;
import com.allen.service.ShoppingCartService;
import com.allen.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author dragon1006xu@gmail.com
 * @create 2022/2/21 15:17
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    UserService userService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    ShoppingCartService shoppingCartService;

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("下单数据：{}", orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(Integer page, Integer pageSize) {
        //设置分页条件，使用Page对象设置
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        //返回的数据封装到Page<OrdersDto>中
        Page<OrdersDto> ordersDtoPage = new Page<>();
        //设置查询条件
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        lambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(ordersPage, lambdaQueryWrapper);
        //将查询出的OrdersPage数据封装到OrdersDtoPage中
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        List<Orders> ordersList = ordersPage.getRecords();
        List<OrdersDto> ordersDtoList = new ArrayList<>();

        for (Orders orders : ordersList) {
            //创建ordersDto对象 将orders填充到ordersDto
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);
            // 创建OrderDetail查询对象
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderDetail::getOrderId, orders.getId());
            List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);
            ordersDto.setOrderDetails(orderDetailList);
            //获取数据将封装到ordersDto
            ordersDtoList.add(ordersDto);
        }
        ordersDtoPage.setRecords(ordersDtoList);
        return R.success(ordersDtoPage);

    }

    //订单明细分页查询
    @GetMapping("/page")
    public R<Page<Orders>> page(Integer page, Integer pageSize, String number, String beginTime, String endTime) {
        log.info("开始时间" + beginTime);
        //设置分页条件
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        //设置查询条件
        LambdaQueryWrapper<Orders> ordersQueryWrapper = new LambdaQueryWrapper<>();
        ordersQueryWrapper.orderByDesc(Orders::getOrderTime);
        ordersQueryWrapper.apply(StringUtils.isNotBlank(beginTime),
                "date_format (order_time,'%Y-%m-%d %H:%i:%s') >= date_format('" + beginTime + "','%Y-%m-%d %H:%i:%s')")
                .apply(StringUtils.isNotBlank(endTime),
                        "date_format (order_time,'%Y-%m-%d %H:%i:%s') <= date_format('" + endTime + "','%Y-%m-%d %H:%i:%s')");
        //添加过滤条件
        ordersQueryWrapper.like(StringUtils.isNotEmpty(number), Orders::getNumber, number);
        orderService.page(ordersPage, ordersQueryWrapper);

        return R.success(ordersPage);
    }

    //订单派送
    @PutMapping
    public R<String> update(@RequestBody Orders orders) {
        //根据订单id查询orders
        Orders order = orderService.getById(orders.getId());
        if (order.getStatus() != null) {
            order.setStatus(orders.getStatus());
            orderService.updateById(orders);
        }
        return R.success("更新成功");
    }

    //再来一单
    @PostMapping("/again")
    public R<ShoppingCart> againSubmit(@RequestBody Map<String, Long> map) {
        //1.获取当前用户订单id
        Long orderId = map.get("id");
        //思路：根据订单id找到菜品或套餐id，添加到购物车中
        //设置查询条件
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId, orderId);
        OrderDetail orderDetail = orderDetailService.getOne(queryWrapper);
        //获取菜品id
        Long dishId = orderDetail.getDishId();
        //获取套餐id
        Long setmealId = orderDetail.getSetmealId();
        //获取当前用户id
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId, userId);
        if (dishId != null) {
            //添加到购物车的是菜品
            lambdaQueryWrapper.eq(ShoppingCart::getDishId, dishId);
        } else {
            //添加到购物车的是套餐
            lambdaQueryWrapper.eq(ShoppingCart::getSetmealId, setmealId);
        }
        //查询当前菜品或者套餐是否在购物车中
        ShoppingCart cartServiceOne = shoppingCartService.getOne(lambdaQueryWrapper);
        if (cartServiceOne != null) {
            Integer number = cartServiceOne.getNumber();
            cartServiceOne.setNumber(number + 1);
            shoppingCartService.updateById(cartServiceOne);
        } else {
            //如果不存在，创建shoppingCart对象，则添加到购物车，数量默认是1
            ShoppingCart shoppingCart = new ShoppingCart();
            //把orderDetail对象数据封装到shoppingCart：两个表数据基本一致
            BeanUtils.copyProperties(orderDetail, shoppingCart, "orderId");
            shoppingCart.setNumber(1);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            cartServiceOne = shoppingCart;
        }
        return R.success(cartServiceOne);
    }
}
